package cn.org.spring.wechar.controller;

import cn.org.spring.common.util.HttpClientUtils;
import cn.org.spring.common.util.MD5Util;
import cn.org.spring.wechar.config.BasicInfo;
import cn.org.spring.wechar.config.WeCharConfig;
import cn.org.spring.wechar.constant.WeCharConstant;
import cn.org.spring.wechar.entity.WeChatUser;
import cn.org.spring.wechar.utils.CacheUtil;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;


@Slf4j
@Controller
@RequestMapping("/v1/weChar")
public class UserInfoController {

    @Autowired
    WeCharConfig charConfig;
    @Autowired
    CacheUtil cacheUtil;
    @Autowired
    BasicInfo basicInfo;


    /**
     * 回调链接
     * 1、获取code -> 获取accessToken ->获取用户基本信息
     */
    @RequestMapping("/getCode")
    public String getCode(@RequestParam("code") String code,
                          @RequestParam("state") String state,
                          HttpServletResponse response,
                          RedirectAttributes attributes) throws IOException {
        System.out.println(code);
        PrintWriter pw = null;
        try {
            pw = response.getWriter();
            // 表示请求是来自微信重定向的请求
            if (WeCharConstant.STATE.equalsIgnoreCase(state)) {
                String userInfo = getAccessToken(code);
                log.info("获取用户的基本信息 【{}】", userInfo);
                WeChatUser weChatUser = JSON.parseObject(userInfo, WeChatUser.class);
                String userId = MD5Util.getMd5(weChatUser.getOpenid());
                attributes.addAttribute("userid", userId);
                Object o = cacheUtil.get("wechatuser:" + userId);
                if (o == null || o == "") {
                    cacheUtil.set("wechatuser:" + userId, weChatUser);
                }
                return "redirect:" + basicInfo.getUrlPrefix() + "/index";
            } else {
                response.setContentType("text/html;charset=utf-8");
                pw.write("<script>alert('授权失败!');</script>");
                pw.flush();
                pw.close();
                log.info("授权失败不是来自于微信的请求");
            }
        } catch (Exception e) {
            e.printStackTrace();
            response.setContentType("text/html;charset=utf-8");
            pw.write("<script>alert('发生后台异常!');</script>");
            pw.flush();
            pw.close();
            log.info("发生后台异常");
        }
        return null;
    }

    /**
     * 获取accessToken 和 openID
     *
     * @param code
     * @return
     * @throws IOException
     */
    public String getAccessToken(String code) throws IOException {
        String s = HttpClientUtils.get(WeCharConstant.OAUTH_GET_AT.replace("APPID", charConfig.getAppId())
                .replace("SECRET", charConfig.getSecret()).replace("CODE", code));
        System.out.println("获取access token " + s);
        String access_token = JSON.parseObject(s).getString("access_token");
        String openid = JSON.parseObject(s).getString("openid");
        return getUserInfo(access_token, openid);
    }

    /**
     * 获取用户基本信息
     *
     * @param accessToken
     * @param openId
     * @return
     * @throws IOException
     */
    public String getUserInfo(String accessToken, String openId) throws IOException {
        return HttpClientUtils.get(WeCharConstant.OAUTH_USER_INFO.replace("ACCESS_TOKEN", accessToken).replace("OPENID", openId));
    }

}